package one.stand.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import one.stand.aop.ApiController;
import one.stand.enums.ResultEnum;
import one.stand.exception.ParamException;
import one.stand.model.ResultModel;
import one.stand.util.IpUtil;
import one.stand.util.Sha256Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: QIK
 * @CreateDate: 2019/5/6 10:37
 */
@Component
public class ParamInterceptor implements HandlerInterceptor {
    protected static final Logger log = LoggerFactory.getLogger(ParamInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        httpServletResponse.setHeader("Content-type", "application/json;charset=UTF-8");
        StringBuffer requestURL = httpServletRequest.getRequestURL();
        log.info("参数前置拦截器1 preHandle： 请求的uri为：" + requestURL.toString());
        try {
            String ip = IpUtil.getIpAddr(httpServletRequest);
            String data=httpServletRequest.getParameter("data");
            String companyKey=httpServletRequest.getHeader("companyKey");
            log.info("请求参数：{}，companyKey:{}",data,companyKey);
            if (o instanceof HandlerMethod) {
                HandlerMethod h = (HandlerMethod) o;
                ApiController apiController = h.getMethodAnnotation(ApiController.class);
                if (apiController != null) {
                    if(apiController.isParam()){
                        if(StringUtils.isEmpty(data)){
                            log.info("参数校验时data为空");
                            throw new ParamException();
                        }
                       String dataJson= Sha256Util.base64ToString(data);
                       JSONObject jsonObject=JSONObject.parseObject(dataJson);
                       jsonObject.put("companyKey",companyKey);
                       jsonObject.put("ip",ip);
                        log.info("参数解密成功：{}",jsonObject.toJSONString());
                        httpServletRequest.setAttribute("request", JSON.toJavaObject(jsonObject,apiController.paramClass()));
                        log.info(JSON.toJSONString(httpServletRequest.getAttribute("request")));
                    }
                }
            }
            return true;
        }catch (ParamException pe){
            ResultModel.returnJson(httpServletResponse,ResultEnum.NO_PARAM);
            return false;
        }catch (Exception e) {
            ResultModel.returnJson(httpServletResponse, ResultEnum.PARAM_CHECK);
            return false;
        }
    }
}
